﻿//设置html根目录字体大小
require(['jquery','../modules/pageSize'],function($,pageSetSize){
    setRootFontSize(pageSetSize);
	var promotionList = [];
	var categoryList = [];
	var subnavList = [];
	var curShowPos = 0;
	var loadedList = [];
	// 渲染懒加载图片
	function renderImgs(pos){
		promotionList[pos].find("img").each(function(){
			if($(this).hasClass("img-lazyload")){
				$(this).attr("src", getDefaultImg($(this).attr("data-original")));
			}
		});
		categoryList[pos].find("img").each(function(){
			if($(this).hasClass("img-lazyload")){
				$(this).attr("src", getDefaultImg($(this).attr("data-original")));
			}
		});
	}
	$(".right-content .category-promote").each(function(i, o){		
		if(i == curShowPos){
			loadedList.push(true);
			$(this).css("display", "block");
		}else{
			loadedList.push(false);
			$(this).css("display", "none");	
		}
		promotionList.push($(this));
	});
	$(".right-content .category-list").each(function(i, o){
		if(i == curShowPos){
			$(this).css("display", "");
		}else{
			$(this).css("display", "none");	
		}
		categoryList.push($(this));
	});
	$(".left-menu a").each(function(i, o){
		if(i == curShowPos){
			$(this).addClass("active");
			renderImgs(i);
		}
		subnavList.push($(this));
		$(this).on("click", function(){
			if(i != curShowPos){
				if(!loadedList[i]){
					loadedList[i] = true;
					renderImgs(i);
				}
				subnavList[i].addClass("active");
				promotionList[i].css("display", "block");
				categoryList[i].css("display", "");
				subnavList[curShowPos].removeClass("active");
				promotionList[curShowPos].css("display", "none");
				categoryList[curShowPos].css("display", "none");
				curShowPos = i;				
			}
		});	
	});
    // 一级分类效果
    var winH = $(window).height();
    var topH = $('.category-bar').height();
    var botH = $('.fixed-main-menu').height();
    $('.left-menu,.right-box').css('height',winH-topH-botH);
});

/**
 * 分类列表 页面渲染 下拉加载页面
 *
 */
require(['jquery','../modules/popup'],function($,popup){
    // 获取参数
    var page =1;
    var category_id,
        _sort,
        _select,
        menuId;
    var res_cur='<div class="text" style="font-size: .26rem; width: 100%; padding-top:.15rem; text-align: center;line-height: 1.5;color:#787878; ">已经显示完全所有商品</div>';
    /*初始化*/
    var counter = 0; /*计数器*/
    var pageStart = 0; /*offset*/
    var pageSize = 10; /*size*/
    var isEnd = false;/*结束标志*/
    var isAjax = false;/*防止滚动过快，服务端没来得及响应造成多次请求*/
    // 首次加载
    getData(pageStart,pageSize,page,category_id,_sort,_select);
    menuOperate();
    /*监听加载更多*/
    $(window).scroll(function(){
        //console.log(isEnd, isAjax);
        //console.log($(document).height() - $(this).scrollTop() - $(this).height());
        /*滚动加载时如果已经没有更多的数据了、正在发生请求时，不能继续进行*/
        if(isEnd == true || isAjax == true){
            return;
        }
        // 当滚动到最底部以上100像素时， 加载新内容
        if ($(document).height() - $(this).scrollTop() - $(this).height()<100){
            counter ++;
            pageStart = counter * pageSize;
            getData(pageStart, pageSize,(counter+page),category_id,_sort,_select);
        }
    });
    // 菜单操作
    function menuOperate(){
        // 二级分类效果
        var de_curr;
        $('.sort-bar li').on('click',function(){
            var curr =$('.sort-bar li').index(this);
            de_curr = curr;
            $(this).addClass('active').siblings().removeClass('active');
            $('.tips').hide();
            $('.tips').eq(curr).show();
            $('body').append('<div class="pop-mask"></div>');
            var str = $('.pop-mask');
            str.hide();
            str.eq(0).show();
        });
        $('.tips').on('click','a',function(){
            $(this).addClass('active').siblings().removeClass('active');
            $(this).parent().hide();
            $('.sort-bar li').eq(de_curr).find('a').remove();
            category_id = $(this).attr("category-id");
            _sort = $(this).attr("sort");
            _select = $(this).attr("select");
            var html = '<a href="javascript:void(0);">'+$(this).text()+'</a>';
            $('.sort-bar li').eq(de_curr).html(html);
            $('.pop-mask').remove();
            isEnd =false;
            counter = 0;
            $('.filter-goods-list ul div.text').remove();
            getData(pageStart,pageSize,page,category_id,_sort,_select)
        });

    }

    function addCartanimate(){
        $('.filter-goods-list li').each(function(){
            $(this).find('.cart').on('click',function(e){
                var _self = $(this);
                e.preventDefault();
                _global.checkPhoner.verifyfunc = function(rs){
                    if(rs){
                        addCartAjax(e,_self);
                        return true;
                    }else{
                        return false;
                    }
                };
                _global.checkPhoner.succfunc =function(){
                    addCartAjax(e,_self);
                };
                _global.checkPhoner.run(e);
            })
        });
    }

    function  addCartAjax(e,_self){
        var goodsInfo = {
            sid: _self.data('sid'),
            pid: _self.data('pid'),
            gid: _self.data('gid'),
            spid:_self.data('spid')};
        //console.log(goodsInfo);
        $.ajax({
            url: '/home/carts/addcart'+getFixedExtraUrl(),
            type: 'post',
            data: {
                'pid': goodsInfo.pid,
                'buyNum': 1,
                'goods_id': goodsInfo.gid,
                'local_id': goodsInfo.sid,
                'spid': goodsInfo.spid,
                'action': 'plus'
            },
            dataType: 'json',
            success: function(data) {
               // console.log(data);
                if(data.status == 2) {
                    popup.alertPopup(data.msg);
                }else if(data.status == 0){
                    popup.alertPopup(data.msg);
                    window.location.href=data.url;
                }else{
                    e.preventDefault();
                    _self.find('label').addClass('animate');
                    setTimeout(function(){
                        _self.find('label').removeClass('animate');
                    },500);
                }
            },
            error: function(err) {
                console.log(err.toString());
                popup.alertPopup('服务器异常，请稍后重试！')
            }

        });

    }
    function getData(offset,size,page,category_id,_sort,_select){
        if(_cat_id){
            if(_sort == undefined && _select == undefined ){
                menuId =category_id;
            }
            if(category_id == undefined && _select == undefined ){
                menuId =+_cat_id+'/sort/'+_sort;
            }
            if(category_id == undefined && _sort == undefined ){
                menuId =+_cat_id+'/select/'+_select;
            }
            if(category_id == undefined  && _sort == undefined && _select == undefined){
                menuId =_cat_id;
            }
            if(category_id == ''  && _sort == undefined && _select == undefined){
                menuId =_cat_id;
            }
            isAjax = true;
            $.ajax({
                url:'/home/GoodsList/ajax/category_id/'+menuId+''+getFixedExtraUrl(),
                type:'GET',
                data:{p:page},
                dataType:'json',
                beforeSend: function () {
                    $("body").append('<div id="pload" style="position:fixed;top:0;z-index:1200;background: rgba(0,0,0,0.3);width:100%;height:100%;margin:auto auto;">' +
                        '<p style="width:2.0rem;height: 2.0rem; margin: 0 auto;text-align: center; position: relative; top: 5rem;">' +
                        '<span style="font-size: .32rem;color: #3c6a63;">加载中...</span>' +
                        '<img src="/Public/Home/images/loading-more.gif" style="display: block;width: .32rem;height: .32rem; margin: 0 auto;"></p>'+
                        '</div>');
                },
                success:function(data){
                    var listData = data.data;
                    //console.log(data);
                    if(listData == null || listData ==0 ){
                        if(data.count == 0 ){
                            $('.filter-goods-list ul').html('');
                            $(".empty-box").show();
                            isAjax = true;
                        }
                    }
                    if(listData){
                        $(".empty-box").hide();
                        isAjax = false;
                        var menuData = data.store_cat_msg;
                        var  sum = listData.length,
                            page_current = data.page,
                            totalPage = data.totalPage;
                        var result = '',
                            menuHtml = '';

                        /************业务逻辑块：实现拼接html内容并append到页面*****************/

                        // console.log(sum, parseInt(page_current),totalPage);
                        /*如果剩下的记录数不够分页，就让分页数取剩下的记录数
                         * 例如分页数是5，只剩2条，则只取2条
                         *
                         * 实际MySQL查询时不写这个不会有问题
                         */

                        if(sum - offset < size ){
                            size = sum - offset;
                        }
                        /*使用for循环模拟SQL里的limit(offset,size)*/
                        if(menuData != undefined && category_id == undefined && _sort == undefined  && _select == undefined && page_current ==1 ){
                            for(var i= 0 ; i<menuData.length; i++){
                                menuHtml+= '<a category-id="'+menuData[i].store_cat_id+'" href="javascript:void(0)">'+menuData[i].cat_name+'</a>'
                            }
                            $('.full-select-category').append(menuHtml);
                        }
                        for(var j= 0 ; j<listData.length; j++){

                            if(listData[j].spec_info == null){
                                listData[j].spec_info = '';
                            }
                            var store_cur = listData[j].store, store_last = listData[j].freez;
                            var store_out = parseInt(store_cur - store_last);
                            result +='<li>';
                                if(store_out > 0){
                                    result +='<a href="/Home/goods/detail/id/'+listData[j].store_pid+'/local_id/'+listData[j].local_id+'/top_local_id/'+yc_pass_arr.top_local_id+'" class="img">'
                                }
                                else {
                                    result +='<a href="/Home/goods/detail/id/'+listData[j].store_pid+'/local_id/'+listData[j].local_id+'/top_local_id/'+yc_pass_arr.top_local_id+'" class="img sold_out">'
                                }
								result +='<img src="'+getDefaultImg(listData[j].image)+'"></a>'+
                                '<a href="/Home/goods/detail/id/'+listData[j].store_pid+'/local_id/'+listData[j].local_id+'/top_local_id/'+yc_pass_arr.top_local_id+'" class="name text-hide">'+listData[j].name+'</a>' +
                                '<p class="des text-hide">'+listData[j].spec_info+'</p>'+
                                '<p class="price"><span class="sale-price">'+listData[j].price+'</span></p>'+
                                // '<p class="price"><span class="sale-price">'+listData[j].price+'</span><span class="old-price">'+listData[j].marketprice+'</span></p>'+
                                '<a href="javascript:void(0);" class="cart" data-sid ="'+listData[j].local_id+'" data-pid ="'+listData[j].product_id+'" data-gid ="'+listData[j].goods_id+'" data-spid ="'+listData[j].store_pid+'" ><label>+1</label></a>'+
                                '</li>';
                        }
                        if(category_id == undefined && _sort == undefined && _select == undefined){
                            $('.filter-goods-list ul').append(result);
                        }
                        else {
                            if(parseInt(page_current)>1){
                                $('.filter-goods-list ul').append(result);
                            }else{
                                $('.filter-goods-list ul').html(result);
                            }

                        }
                        if ( parseInt(page_current)  >= totalPage){
                            $('.filter-goods-list ul').append(res_cur);
                            isEnd = true;
                        }
                    }
                    addCartanimate();
                },
                complete: function () {
                    $("#pload").remove();
                },
                error:function(){
                    popup.alertPopup('服务器异常,请稍后重试！');
                }
            });
        }
    }
});